package org.netty.framework.core.config;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelOption;
import io.netty.util.internal.SystemPropertyUtil;

/**
 * netty server的配置
 * 
 * @author chenfanglin
 * @date 2018年9月20日上午10:42:45
 */
public class NettyServerConfig {

	/**
	 * http服务的端口
	 */
	private static int httpServerPort;

	/**
	 * tcp服务的端口
	 */
	private static int tcpServerPort;

	/**
	 * websocket服务的端口
	 */
	private static int websocketServerPort;

	/**
	 * Socket参数,BACKLOG用于构造服务端套接字ServerSocket对象，标识当服务器请求处理线程全满时，用于临时存放已完成三次握手的请求的队列的最大长度。如果未设置或所设置的值小于1，netty的默认值128
	 */
	private static int DEFAULT_SO_BACKLOG = 1024;

	/**
	 * Socket参数,连接保活，默认值为False。启用该功能时，TCP会主动探测空闲连接的有效性。可以将此功能视为TCP的心跳机制，需要注意的是：默认的心跳间隔是7200s即2小时。Netty默认关闭该功能
	 */
	private static boolean DEFAULT_SO_KEEPALIVE = true;

	/**
	 * TCP参数,设置为非延迟发送，为true则不组装成大包发送，收到东西马上发出
	 */
	private static boolean DEFAULT_TCP_NODELAY = true;

	/**
	 * Socket参数,设置每一个非主监听连接的端口可以重用
	 */
	private static boolean DEFAULT_SO_REUSEADDR = true;

	static {
		httpServerPort = SystemPropertyUtil.getInt("netty.http.server.port", 8666);
		tcpServerPort = SystemPropertyUtil.getInt("netty.tcp.server.port", 8667);
		websocketServerPort = SystemPropertyUtil.getInt("netty.websocket.server.port", 8668);
	}

	/**
	 * 给boss线程池和worker线程池中的channel设置参数
	 * 
	 * @param serverBootstrap
	 */
	public static void setTcpChannelOptions(ServerBootstrap serverBootstrap) {
		serverBootstrap.option(ChannelOption.SO_BACKLOG, DEFAULT_SO_BACKLOG);
		serverBootstrap.option(ChannelOption.SO_REUSEADDR, DEFAULT_SO_REUSEADDR);
		serverBootstrap.childOption(ChannelOption.TCP_NODELAY, DEFAULT_TCP_NODELAY);
		serverBootstrap.childOption(ChannelOption.SO_KEEPALIVE, DEFAULT_SO_KEEPALIVE);
	}

	public static int getHttpServerPort() {
		return httpServerPort;
	}

	public static void setHttpServerPort(int httpServerPort) {
		NettyServerConfig.httpServerPort = httpServerPort;
	}

	public static int getTcpServerPort() {
		return tcpServerPort;
	}

	public static void setTcpServerPort(int tcpServerPort) {
		NettyServerConfig.tcpServerPort = tcpServerPort;
	}

	public static int getWebsocketServerPort() {
		return websocketServerPort;
	}

	public static void setWebsocketServerPort(int websocketServerPort) {
		NettyServerConfig.websocketServerPort = websocketServerPort;
	}

}
